from selenium import webdriver
from PIL import Image
import io
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 初始化WebDriver
driver = webdriver.Chrome()
driver.get("http://valser.org/reg/2024/")
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, "#content > div.identity-content > div.identity-form > form > div:nth-child(3) > div > div > img"))
)
# 等待页面加载并定位到验证码图片元素
captcha_element = driver.find_element_by_css_selector("#content > div.identity-content > div.identity-form > form > div:nth-child(3) > div > div > img")  # 更新这个选择器以匹配你的验证码图片

# 获取验证码元素的位置和大小
location = captcha_element.location
size = captcha_element.size
# 截取整个页面截图

png = driver.get_screenshot_as_png()  # 获取屏幕截图的PNG格式图片数据

# 使用Pillow处理图片
image = Image.open(io.BytesIO(png))
image.save('captcha.png')


# 计算验证码图片的位置
left = 1240
top = 550
bottom = 650
right = 1530

print(left, top, right, bottom)

# 裁剪验证码图片
image = image.crop((left, top, right, bottom))

# 保存验证码图片
image.save('captcha1.png')

# 关闭WebDriver
driver.quit()
